<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row>
          <a-col :span="12" >
            <a-form-model-item label="配方年" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaYear">
              <a-input-number v-model="model.formulaYear" placeholder="请输入配方年" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="配方编码" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaCode">
              <a-input v-model="model.formulaCode" placeholder="" :disabled="true"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="配方号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaNumber">
              <a-input v-model="model.formulaNumber" placeholder="请输入配方号" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="配方名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaDefine">
              <a-input v-model="model.formulaDefine" placeholder="请输入配方名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="配方类别" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaCategory">
              <j-dict-select-tag type="list" v-model="model.formulaCategory" dictCode="formula_category" placeholder="请选择配方类别" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="配方类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaType">
              <j-dict-select-tag type="list" v-model="model.formulaType" dictCode="formula_type" placeholder="请选择配方类型" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" >
            <a-form-model-item label="类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="formulaDesc">
              <j-dict-select-tag type="list" v-model="model.formulaDesc" dictCode="formula_desc" placeholder="请选择类型" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
      <!-- 子表单区域 -->
    <a-tabs v-model="activeKey" @change="handleChangeTabs">
      <a-tab-pane tab="配方物料详情" :key="refKeys[0]" :forceRender="true">
        <j-vxe-table
          keep-source
          :ref="refKeys[0]"
          :loading="ipsTslFormulaMaterialDetailTable.loading"
          :columns="ipsTslFormulaMaterialDetailTable.columns"
          :dataSource="ipsTslFormulaMaterialDetailTable.dataSource"
          :maxHeight="300"
          :disabled="formDisabled || !model.formulaDesc"
          :rowNumber="true"
          :rowSelection="true"
          :toolbar="true"
          @edit-closed="editClosedEvent"
          @popup-change="handlePopupChange"
          />
      </a-tab-pane>
    </a-tabs>
  </a-spin>
</template>

<script>

import { getAction, httpAction } from '@/api/manage'
  import { JVxeTableModelMixin } from '@/mixins/JVxeTableModelMixin.js'
  import { JVXETypes } from '@/components/jeecg/JVxeTable'
  import { getRefPromise,VALIDATE_FAILED} from '@/components/jeecg/JVxeTable/utils/vxeUtils.js'
  import { validateDuplicateValue } from '@/utils/util'
  import JFormContainer from '@/components/jeecg/JFormContainer'
  import { ajaxGetDictItems } from '@api/api'
  import moment from 'dayjs'

  export default {
    name: 'IpsTslFormulaListForm',
    mixins: [JVxeTableModelMixin],
    components: {
      JFormContainer,
    },
    data() {
      return {
        currentEditRow: null, // 用于跟踪当前编辑的行
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        model:{
          formulaYear: moment().format('YYYY'),
          formulaCode: '',
         },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        validatorRules: {
           formulaDefine: [
              { required: true, message: '请输入配方名称!'},
           ],
            formulaYear: [
              {
                validator: (rule, value, callback) => {
                  if (value < 0) {
                    callback("配方年不能为负数!");
                  } else {
                    callback();
                  }
                },
                trigger: 'blur'
              }
            ],
        formulaDesc: [
          { required: true, message: '请先选择类型!' }
        ]
        },
        refKeys: ['ipsTslFormulaMaterialDetail', ],
        tableKeys:['ipsTslFormulaMaterialDetail', ],
        activeKey: 'ipsTslFormulaMaterialDetail',
        // 配方物料详情
        ipsTslFormulaMaterialDetailTable: {
          loading: false,
          dataSource: [],
          columns: [
            {
              title: 'material_id',
              key: 'materialId',
              type: "hidden"
            },
            {
              title: '物料编码',
              key: 'materialCode',
              type: JVXETypes.popup,
              popupCode:"formula_material_detail",
              field:"id,code,name,none_spec,me_unit",
              orgFields:"id,code,name,none_spec,me_unit",
              destFields:"materialId,materialCode,materialName,materialSpec,materialUnit",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              param: {formulaAttribute: '1'},
              // 添加触发方式，确保选择后能触发事件
              triggerChange: true
            },
            {
              title: '物料名称',
              key: 'materialName',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '规格型号',
              key: 'materialSpec',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: '单位',
              key: 'materialUnit',
              type: JVXETypes.input,
              dictCode:"ji_unit",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
              formatter: ({cellValue}) => {
                const item = this.dictInfos.find(item => item.value === cellValue);
                return item ? item.text : cellValue;
              }
            },
            {
              title: '是否自带料',
              key: 'isSelfProvided',
              type: JVXETypes.select,
              options:[],
              dictCode:"yn",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'0',
            },
            {
              title: '配方%',
              key: 'formulaProportion',
              type: JVXETypes.input,
              width: "200px",
              placeholder: '请输入${title}',
              defaultValue: '',
              // 动态禁用（如果是液碱）
              disabled: ({ row }) => this.model.formulaDesc !== '2' && row.materialName && /液碱/i.test(row.materialName),
              validateRules: [
                {
                  pattern: /^((100(\.0{1,4})?)|([1-9]?\d)(\.\d{1,4})?|0(\.\d{1,4})?)$/,
                  message: '请输入0-100之间的数值（最多4位小数）'
                }
              ]
            },
            {
              title: '实际数量',
              key: 'actualNumber',
               type: JVXETypes.input,
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              /*validateRules: [
                {
                  pattern: /^-?\d+(\.\d{1,2})?$/,
                  message: '请输入最多两位小数的数值'
                }
              ]*/
            },
            /*{
              title: '配方公式',
              key: 'formulaExpression',
              type: JVXETypes.select,
              options: this.formulaOptions,
              //dictCode:"ips_formula_info,formula_name,id",
              width:"200px",
              placeholder: '请输入${title}',
              defaultValue:'',
              // 添加格式化函数
              formatter: ({ cellValue }) => {
                const item = this.formulaOptions.find(opt => opt.value === cellValue);
                return item ? item.label : cellValue;
              }
            },*/
            {
              title: '配方公式',
              key: 'formulaExpression',
              type: JVXETypes.input,
              width:"300px",
              placeholder: '请输入${title}',
              defaultValue:'',
              disabled: true,
            },
            {
              title: 'material_code',
              key: 'material_code',
              type:"hidden"
            },

            {
              title: 'material_name',
              key: 'material_name',
              type:"hidden"
            },

            {
              title: 'material_spec',
              key: 'material_spec',
              type:"hidden"
            },

            {
              title: 'material_unit',
              key: 'material_unit',
              type:"hidden"
            },
          ]
        },
        url: {
          add: "/ipstslformulalist/ipsTslFormulaList/add",
          edit: "/ipstslformulalist/ipsTslFormulaList/edit",
          queryById: "/ipstslformulalist/ipsTslFormulaList/queryById",
          generateFormulaCode: "/ipstslformulalist/ipsTslFormulaList/generateFormulaCode",
          getFormulaResult: "/ipstslformulalist/ipsTslFormulaList/getFormulaResult",
          queryFilteredFormulas: "/ipstslformulalist/ipsTslFormulaList/queryFilteredFormulas",
          ipsTslFormulaMaterialDetail: {
            list: '/ipstslformulalist/ipsTslFormulaList/queryIpsTslFormulaMaterialDetailByMainId'
          },
        },
        dictInfos: [],
        formulaOptions: [],
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      this.loadDictData()
    },
    methods: {
      request(formData) {
        let url = this.url.add, method = 'post'
        if (this.model.id) {
          url = this.url.edit
          method = 'put'
        }else {
          formData.ipsTslFormulaMaterialDetailList.forEach((element) => {
            element.id = null
          })
        }
        this.confirmLoading = true
        console.log("formData===>",formData);
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.message)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      },
      async copy(record) {
        //原先操作
        console.log("gggggggg",record)
        this.eachAllTable((item) => {
          //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
          setTimeout(()=>{
            item.addRows()
          }, 30)
          //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        });
        this.edit(record);
        //重设formulaCode
        let defaultCode = await this.generateTslDefaultCode();
        this.model.formulaCode = defaultCode;
        this.model.createTime=null
        this.model.createBy=null
        this.model.id=null
      },

      // 修改 handlePopupChange 方法，处理物料选择后的逻辑
      handlePopupChange(e) {
        console.log("-----------*********-----------："+1)
        // 获取当前编辑的行和列信息
        const { row, column } = e;

        // 只处理物料编码列的变更
        if (column.property === 'materialCode' || column.key === 'materialCode') {
          // 更新行数据
          const existingRowIndex = this.ipsTslFormulaMaterialDetailTable.dataSource.findIndex(r => r === row);
          if (existingRowIndex === -1) {
            this.ipsTslFormulaMaterialDetailTable.dataSource.push({...row});
          } else {
            this.$set(this.ipsTslFormulaMaterialDetailTable.dataSource, existingRowIndex, {...row});
          }
          // 自动设置配方%为0（如果是液碱）
          if (row.materialName && row.materialName.includes('液碱')) {
            this.$set(row, 'formulaProportion', '0'); // 强制设为0
            this.$nextTick(() => {
              this.calculateLyeMaterial(row); // 立即计算
            });
          }

          // 如果是磺酸变更，更新所有液碱
          if (row.materialName && /磺酸/i.test(row.materialName)) {
            this.updateAllLyeMaterials();
          }
          // // 如果不存在，则创建新的行数据
          // if (existingRowIndex === -1) {
          //   const newMaterial = {
          //     materialId: row.materialId,  // 假设 row 中包含这些信息
          //     materialCode: row.materialCode,
          //     materialName: row.materialName,
          //     materialSpec: row.materialSpec,
          //     materialUnit: row.materialUnit,
          //     formulaExpression: '', // 可初始化或计算
          //     actualNumber: '' // 可初始化或计算
          //   };
          //   this.ipsTslFormulaMaterialDetailTable.dataSource.push(newMaterial);
          // } else {
          //   // 如果存在，则更新现有行
          //   this.$set(this.ipsTslFormulaMaterialDetailTable.dataSource, existingRowIndex, {
          //     ...this.ipsTslFormulaMaterialDetailTable.dataSource[existingRowIndex],
          //     materialCode: row.materialCode,
          //     materialId: row.materialId,
          //     materialName: row.materialName,
          //     materialSpec: row.materialSpec,
          //     materialUnit: row.materialUnit
          //   });
          // }
          // // 根据物料名称进行其他处理，例如计算
          // if (row.materialName && row.materialName.includes('液碱')) {
          //   this.$nextTick(() => {
          //     this.calculateLyeMaterial(row);
          //   });
          // } else if (row.formulaProportion) {
          //   this.$nextTick(() => {
          //     this.calculateActualNumber(row, existingRowIndex);
          //   });
          // }
          //
          // // 特殊处理液碱
          // if (row.materialName && row.materialName.includes('液碱')) {
          //   this.$nextTick(() => {
          //     this.calculateLyeMaterial(row);
          //   });
          // }
        }
      },

// 添加专门计算液碱物料的方法
      calculateLyeMaterial(row) {
        // formula_desc为2时不强制设为0
        if (this.model.formulaDesc !== '2') {
          this.$set(row, 'formulaProportion', '0');
        }

        // formula_desc为2时使用简化计算
        if (this.model.formulaDesc === '2') {
          const formulaProportion = parseFloat(row.formulaProportion) || 0;
          this.$set(row, 'formulaExpression', '[配方% ÷ 100]');
          this.$set(row, 'actualNumber', (formulaProportion / 100).toFixed(4));
          return;
        }

        // 原有磺酸检查逻辑
        const sulfonicAcidRow = this.ipsTslFormulaMaterialDetailTable.dataSource.find(r =>
          r.materialName && /磺酸/i.test(r.materialName)
        );

        const formulaExpression = '[磺酸实际数量 × 0.132 / 0.32]';
        let actualNumber = 0;

        if (sulfonicAcidRow?.actualNumber) {
          actualNumber = parseFloat(sulfonicAcidRow.actualNumber) * 0.132 / 0.32;
        } else {
          this.$message.error('请先添加并计算磺酸物料的实际数量！');
          this.$set(row, 'formulaExpression', '需要先设置磺酸物料');
          this.$set(row, 'actualNumber', '');
          return;
        }

        this.$set(row, 'formulaExpression', formulaExpression);
        this.$set(row, 'actualNumber', actualNumber.toFixed(4));
      }
      ,

// 修改 editClosedEvent 方法
      editClosedEvent({ row, column }) {

        // 磺酸的实际数量变化时触发液碱更新
        if (column.property === 'actualNumber' && row.materialName && /磺酸/i.test(row.materialName)) {
          this.updateAllLyeMaterials();
        }
        const existingRowIndex = this.ipsTslFormulaMaterialDetailTable.dataSource.findIndex(r => r === row);
        // 处理配方百分比或物料编码的变更
        if (['formulaProportion', 'materialCode'].includes(column.property)) {
          if (!row.materialId || !row.materialName) {
            return;
          }

          // 如果当前行不存在，则添加
          if (existingRowIndex === -1) {
            this.ipsTslFormulaMaterialDetailTable.dataSource.push(row);
          } else {
            // 更新现有行
            this.$set(this.ipsTslFormulaMaterialDetailTable.dataSource, existingRowIndex, row);
          }

          // 确保有配方百分比
          if (!row.formulaProportion) {
            return;
          }

          // 如果是液碱物料
          if (row.materialName.includes('液碱')) {
            this.calculateLyeMaterial(row);
          } else {
            this.calculateActualNumber(row, existingRowIndex);
          }
        }
      },
      // 更新所有液碱物料
      updateAllLyeMaterials() {
        this.ipsTslFormulaMaterialDetailTable.dataSource.forEach(row => {
          if (row.materialName && /液碱/i.test(row.materialName)) {
            this.calculateLyeMaterial(row);
          }
        });
      },
      // 更新所有液碱物料的计算
      updateLyeCalculations() {
        console.log('开始更新所有液碱物料');

        // 查找磺酸物料行
        const sulfonicAcidRow = this.ipsTslFormulaMaterialDetailTable.dataSource.find(r =>
          r.materialName && r.materialName.includes('磺酸')
        );

        if (sulfonicAcidRow && sulfonicAcidRow.actualNumber) {
          console.log('找到磺酸物料，实际数量:', sulfonicAcidRow.actualNumber);

          // 查找所有液碱物料并更新
          this.ipsTslFormulaMaterialDetailTable.dataSource.forEach(row => {
            if (row.materialName && row.materialName.includes('液碱')) {
              console.log('更新液碱物料:', row.materialName);
              const formulaExpression = '[磺酸实际数量 × 0.132 / 0.32]';
              const actualNumber = parseFloat(sulfonicAcidRow.actualNumber) * 0.132 / 0.32;

              this.$set(row, 'formulaExpression', formulaExpression);
              this.$set(row, 'actualNumber', actualNumber.toFixed(4));
            }
          });
        } else {
          console.log('未找到磺酸物料或实际数量为空');
        }
      },


      // 根据物料类型计算实际数量
      calculateActualNumber(row, rowIndex) {
        const formulaProportion = parseFloat(row.formulaProportion) || 0;
        let actualNumber = 0;
        let formulaExpression = '';

        // formula_desc为2时的简化计算
        if (this.model.formulaDesc === '2') {
          formulaExpression = '[配方% ÷ 100]';
          actualNumber = formulaProportion / 100;
        }
        // 原有计算逻辑（formula_desc为1或3）
        else {
          if (row.materialName.includes('磺酸')) {
            formulaExpression = '[(配方% × 323 × 10)÷(0.96 × 345 × 1000)]';
            actualNumber = (formulaProportion * 323 * 10) / (0.96 * 345 * 1000);
          }
          else if (row.materialName.includes('液碱')) {
            const sulfonicAcidRow = this.ipsTslFormulaMaterialDetailTable.dataSource.find(r =>
              r.materialName && r.materialName.includes('磺酸')
            );
            if (sulfonicAcidRow?.actualNumber) {
              formulaExpression = '[磺酸实际数量 × 0.132 / 0.32]';
              actualNumber = parseFloat(sulfonicAcidRow.actualNumber) * 0.132 / 0.32;
            } else {
              this.$message.warning('请先设置磺酸物料的配方百分比！');
              formulaExpression = '[磺酸实际数量 × 0.132 / 0.32]';
              actualNumber = 0;
            }
          }
          else if (row.materialName.includes('泡花碱')) {
            formulaExpression = '[配方% ÷ (0.31 × 100)]';
            actualNumber = formulaProportion / (0.31 * 100);
          }
          else {
            formulaExpression = '[配方% ÷ 100]';
            actualNumber = formulaProportion / 100;
          }
        }

        this.$set(row, 'formulaExpression', formulaExpression);
        this.$set(row, 'actualNumber', actualNumber.toFixed(4));
      },


      // 校验第一行必须是磺酸物料
      validateFirstRowMaterial() {
        // formula_desc为2时不强制要求磺酸
        if (this.model.formulaDesc === '2') return true;

        if (this.ipsTslFormulaMaterialDetailTable.dataSource.length > 0) {
          const firstRow = this.ipsTslFormulaMaterialDetailTable.dataSource[0];
          if (firstRow.materialName && !firstRow.materialName.includes('磺酸')) {
            this.$message.error('第一个物料必须选择包含"磺酸"字样的物料！');
            return false;
          }
        }
        return true;
      },

      // 重写 validateSubForm 方法，添加自定义校验
      validateSubForm(allValues) {
        return new Promise((resolve, reject) => {
          // 先校验第一行物料
          if (!this.validateFirstRowMaterial()) {
            reject({
              error: VALIDATE_FAILED,
              index: 0
            });
            return;
          }

          // 继续原有校验逻辑
          Promise.all([
          ]).then(() => {
            resolve(allValues);
          }).catch(e => {
            if (e.error === VALIDATE_FAILED) {
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index];
            } else {
              console.error(e);
            }
            reject(e);
          });
        });
      },

      loadDictData() {
        ajaxGetDictItems('ji_unit', null).then((res) => {
          if (res.success) {
            this.dictInfos = res.result
          }
        })
      },
      addBefore(){
        this.ipsTslFormulaMaterialDetailTable.dataSource=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        this.loadFormulaOptions();
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.ipsTslFormulaMaterialDetail.list, params, this.ipsTslFormulaMaterialDetailTable)
        }
      },

      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)
        return {
          ...main, // 展开
          ipsTslFormulaMaterialDetailList: allValues.tablesValue[0].tableData,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      async generateTslDefaultCode() {
        try {
          const res = await getAction(this.url.generateFormulaCode, { sourceFrom: 'tsl' })
          if (res.success) {
            return res.result
          } else {
            this.$message.warning(res.message)
            return ''
          }
        } catch (e) {
          console.error("生成编码失败", e)
          return ''
        }
      },
      // 覆写add() -> 重设formulaCode
      async add() {
        //原先操作
        if (typeof this.addBefore === 'function') this.addBefore();
        this.eachAllTable((item) => {
          //update-begin-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
          setTimeout(()=>{
            item.addRows()
          }, 30)
          //update-end-author:taoyan date:20210315 for: 一对多jvex 默认几行不好使了 LOWCOD-1349
        });
        if (typeof this.addAfter === 'function') this.addAfter(this.model);
        this.edit(this.model);
        //重设formulaCode
        let defaultCode = await this.generateTslDefaultCode();
        this.model.formulaCode = defaultCode;
      },
      loadFormulaOptions() {
        try {
          getAction(this.url.queryFilteredFormulas, { formulaAttribute: '1' }).then(res=>{
            if (res.success) {
              this.formulaOptions = res.result.map(item => ({
                value: item.id,
                title: item.formulaName,
                label: item.formulaName
              }));
              // 1. 更新本地列配置
              let newColumns = [...this.ipsTslFormulaMaterialDetailTable.columns];
              let formulaCol = newColumns.find(col => col.key === 'formulaExpression');
              if (formulaCol) {
                formulaCol.options = this.formulaOptions;
                this.ipsTslFormulaMaterialDetailTable.columns = newColumns; // 确保响应式更新
              }
              // 2. 手动更新 JVxeTable 实例的列配置
              const jvxeTableRef = this.$refs[this.refKeys[0]];
              if (jvxeTableRef) {
                jvxeTableRef.setColumns(newColumns); // 关键：触发列更新
              }
            } else {
              console.error('加载配方公式失败:', res.message);
            }
          });
        } catch (error) {
          console.error('加载配方公式异常:', error);
        }
      },
    }
  }
</script>

<style scoped>
</style>